﻿(function () {
	// 定制UIRouter的规则
	function crudRouteProvider ($stateProvider, $urlRouterProvider, ROOT_STATE_NAME, MENU_CONTENT) {

		this.$get = angular.noop;
		
		this.routesFor = function (resourceName, urlPrefix) {

			var baseUrl = resourceName.toLowerCase()
				, baseRoute = baseUrl
				, baseStateName = ROOT_STATE_NAME + '.' + urlPrefix + '/' + baseUrl;

			// 如果urlPrefix存在，设置baseUrl
			if (angular.isString(urlPrefix) && urlPrefix !== '') {
				baseUrl = urlPrefix + '/' + baseUrl;
			}

			// 如果提供根目录，则添加跟目录
            baseRoute = '/' + urlPrefix + '/' + baseRoute;

			// 创建templateUrl
			var templateUrl = function (operation) {
				return baseUrl + '/' + resourceName.toLowerCase() + '-' + operation.toLowerCase() + '.tpl.html';
			};

			// 为路由页面注入controller
			var controllerName = function (operation) {
				return resourceName + operation + 'Ctrl';
			};

			// 页面跳转
			var routeBuilder = {

				// 调用页面下的list模板
				whenList : function (resolveFns) {
					this.when(baseStateName, {
						url : baseRoute
						, templateUrl : templateUrl('List')
						, controller : controllerName('List')
						, resolve : resolveFns
					});
					return routeBuilder;
				},

				// 创建新增页面路由
				whenNew : function (resolveFns) {
					this.when(baseStateName + '/new', {
						url : baseRoute + '/new'
						, templateUrl : templateUrl('Edit')
						, controller : controllerName('Edit')
						, resolve : resolveFns
					});
					return routeBuilder;
				},

				// 创建修改页面路由
				whenEdit : function (resolveFns) {
					this.when(baseStateName + '/edit', {
						url : baseRoute + '/edit/:itemId'
						, templateUrl : templateUrl('Edit')
						, controller : controllerName('Edit')
						, resolve : resolveFns
					});
					return routeBuilder;
				},

				// 调用原生的路由
				when : function (stateName, option) {
                    var views = option.views ? views = option.views : views = [MENU_CONTENT];
                    var data = {
                        url : option.url
                        , views : {}
                    };
                    for (var i = 0, len = views.length; i < len; i++) {
                        var view = views[i];
                        data.views[view] = {
                            templateUrl : option.templateUrl
                            , controller : option.controller
                            , resolve : option.resolve
                        };
                    }

					$stateProvider.state(stateName, data);
					return routeBuilder;
				}
			};

			return routeBuilder;
		}
	};

	crudRouteProvider.$inject = ['$stateProvider', '$urlRouterProvider', 'ROOT_STATE_NAME', 'MAIN_CONTENT'];
	angular.module('services.crudRouteProvider', ['ui.router', 'COMMON_DEFINE']).provider('crudRoute', crudRouteProvider);
}) ();
